App.controller("giftLibraryCtrl",function($scope, $rootScope, $location, $http, $compile, $stateParams, $timeout, path, publicService) {
	
	$scope.search = {};		//搜索参数
	$scope.form = {};		//表单参数
	
	
	$scope.submit_show = true;		//提交（显示）

	$scope.creator_show = false;   	//创建者（显示）
	$scope.addGift_show = false;	//添加礼品（显示）
	
	$scope.creater_hidden = false;   //创建者（隐藏）
	
	var alertModel = {};	//alert模态框
	
	
	
	if(userInfo.user_level==0){	//开发者
		$scope.creator_show = true;   
	}else if(userInfo.user_level==3){	//三级用户
		$scope.creator_show = true;
	}else if(userInfo.user_level==2){	//二级用户
		$scope.addGift_show = true;
		
		$scope.creater_hidden = true; 
	}else if(userInfo.user_level==1){	//一级用户
		$scope.creater_hidden = true; 
	}
	//表格对象
	$scope.gridOptions = {
			dataSource : {
				transport : {
					read : {
						url : path+"/server/selectNewGiftActivityPage",
						type : 'POST',
						dataType : "json",
						contentType : "application/json"
					},
					parameterMap : function(options, operation) {
						if (operation == "read") {
							var sort = [{dir:"desc",field:"create_time"}];
							if(options.sort!=null && options.sort.length>0 ){
								if(options.sort[0].field=="createTime"){
									options.sort[0].field="create_time";
								}else{
									options.sort[0].field="create_time";
								}
								
								sort=options.sort;
							}
							
							var parameter = {
								page : options.page, //当前页
								pageSize : options.pageSize,
								param:{
									name: $scope.search.giftName,
									grade: $scope.search.grade,
									creator:$scope.search.creator,    //创建者
									sort:sort
								}
							};
							console.log('查询参数',parameter);
							return kendo.stringify(parameter);
						}
					},
				},
				pageSize : 10,
				serverPaging : true,
				serverSorting: true,
				schema : {
					data : function(d) {
						return d.data;
					},
					total : function(d) {
						return d.total; //总条数
					}
				},
			},
			pageable : {  //分页
				pageSizes: [10, 20, 50, 100],  //每页显示记录数
			  },  
			sortable: {   //排序
				//allowUnsort: false,  //允许无序
			    mode: "single"     //排序模式：single，multiple
			  },
			editable: false,  //true：单个编辑；popup：弹出新页面编辑
			dataBound: function () {   //序号
		        var rows = this.items();
		        var page = this.pager.page() - 1;
		        var pagesize = this.pager.pageSize();
		        $(rows).each(function () {
		            var index = $(this).index() + 1 + page * pagesize;
		            var rowLabel = $(this).find(".row-number");
		            $(rowLabel).html(index);
		        });
		        
		        console.log("【Grid 数据绑定成功】");
		    	$('.fancybox').fancybox();
		    },
			columns : [
					{    
						title : "序号",
						field : "id", 
						width : "50px",
						template:"<input type='checkbox' class='recordClass' value='#: id #' />"+"<span class='row-number subTitle'></span>"
					},
					{
						field : "img_url",         
						title : "礼品图片",     
						width : "100px",
						template: function(e){ 
							var html = ('<a class="fancybox" href="'+e.img_url+'" data-fancybox-group="gallery_'+e.id+'" title="缩略图">'
											+'<img src="'+e.img_url+'" class="tableImage" style="width:120px;"/>'
										+'</a>');
	
							return html;
						}
					},
					{
						field : "grade",         
						title : "等级",     
						width : "100px"
					},
					{
						field : "name",         
						title : "名称",     
						width : "100px"
					},
					{
						field : "value",         
						title : "价值",     
						width : "100px"
					},
					{
						field : "inventory",         
						title : "库存数量",     
						width : "100px"
					},
					{
						field : "num",         
						title : "活动用量",     
						width : "100px"
					},
					{
						field : "create_time",         
						title : "创建时间",     
						width : "100px"
					},
					{
						field : "creator",         
						title : "创建者",     
						width : "100px",
						hidden: $scope.creater_hidden,
					},
					{
						field : "",         
						title : "操作",     
						width : "100px",
						template: function(e){
					    	var html = '';
					    	
					    	if(userInfo.user_level==2){
					    		html += '<div class="operation" ng-click="lookOrEdit('+e.id+',2)">编辑</div>';
					    	}else{
					    		html += '<div class="operation" ng-click="lookOrEdit('+e.id+',1)">查看</div>';
					    	}

					    	return html;
					    },
					}
			]
	};
	
	//查询
	$scope.search = function(){
		$scope.grid.dataSource.page(1);
	}
	
	//全选，取消
	$scope.chooseAll = function(className,flag){
		publicService.chooseAllByClassName(className,flag);
	}
	
	//导出表格数据（1：筛选导出，2：选中导出）  
	$scope.downloadTableData = function(type){
		var paramObj = {};
		
		if(type==1){	//筛选导出
			paramObj = {
					page : 1, 
					pageSize : 10,
					ispage:false,
					param:{
						name: $scope.search.giftName,
						grade: $scope.search.grade,
						principal:$scope.search.creatName    //创建者
					}
			};
		}else if(type==2){	//选中导出
			var ids = publicService.getChooseValueByClassName("recordClass");
			if(ids.length==0){
				$scope.alertMessage("请选择礼品！");
				return;
			}
			
			paramObj = {
					page : 1, 
					pageSize : 10,
					param:{
						ids: ids
					}
			};
		}

		var requestUrl = path+"/server/export";		//请求路径
		var exportModule = "gift_module";			//模块名称
		var form = $("<form method='POST' action='"+requestUrl+"' target='_self'>"
						+"<input type='hidden' name='module_code' value='"+exportModule+"'/>"
						+"<input type='hidden' name='page' value='"+angular.toJson(paramObj)+"'/>"
					+"</form>");
		console.log("【表单参数】",form.serializeArray());
	    $(document.body).append(form);
	    form.submit();	
	}
	
	//提示信息
	$scope.alertMessage = function(message){
		alertModel.pannel = jqueryAlert({
			content: message,
			modal: true
		});
	}
	
	//打开礼品窗口
	$scope.openGiftWindow = function(){
		$scope.form = {};
		publicService.removeUploadImage("gift_img","gift_url");
		$scope.submit_show = true;
		$(".windowForm").find("input").removeAttr("disabled");
		$scope.giftWindow.center().open();   //打开弹框
	}
	
	//添加礼品
	$scope.addGift = function(){
		$scope.form.img_url = $("#gift_url").val();
		
		if(!$scope.form.img_url){
			$scope.alertMessage("请上传礼品图片！");
			return;
		}
		if(!$scope.form.grade){
			$scope.alertMessage("请输入礼品等级！");
			return;
		}
		if(!$scope.form.value){
			$scope.alertMessage("请输入礼品价值！");
			return;
		}else{
			if($scope.form.value<0){
				$scope.alertMessage("礼品价值请输入正确的数值！");
				return;
			}
		}
		if(!$scope.form.inventory){
			$scope.alertMessage("请输入礼品数量！");
			return;
		}else{
			if(!publicService.checkIsUpNumber($scope.form.inventory)){
				$scope.alertMessage("礼品数量请输入正确的数值！");
				return;
			}
		}
		
		var url = '';
		if(!$scope.form.id){
			url = path+'/server/addGift';
		}else{
			url = path+'/server/updateGiftOne';
		}
		
		$http({
			   url: url,
			   method: 'POST',   
			   data: angular.toJson($scope.form)
		}).success(function(data){
			if(data.code==0){
				$scope.giftWindow.close();
				$scope.alertMessage("成功！");
				$scope.search();
			}else{
				$scope.alertMessage("失败！");
			}
		}).error(function(data){
			console.warn(data);   
		})
	}
	
	//查看或编辑
	$scope.lookOrEdit = function(id,type){	
		
		$http({
			   url:	path+'/server/selectGiftOne/'+id,
			   method: 'GET'   
		}).success(function(data){
			if(data.code==0){
				var giftInfo = data.result;
				
				$scope.form.id = giftInfo.id;
				publicService.showUploadImage("gift_img","gift_url",giftInfo.img_url);
				$scope.form.grade = giftInfo.grade;
				$scope.form.name = giftInfo.name;
				$scope.form.value = Number(giftInfo.value);
				$scope.form.inventory = giftInfo.inventory;
				$scope.giftWindow.center().open();   //打开弹框
				
				if(type==1){	//查看
					$scope.submit_show = false;
					$(".windowForm").find("input").attr("disabled","disabled");
				}else{
					$scope.submit_show = true;
					$(".windowForm").find("input").removeAttr("disabled");
				}
			}else{
				$scope.alertMessage("失败！");
			}
		}).error(function(data){
			alert(data);   
		})
	}
	
	
	publicService.uploadImage("gift","gift_img","gift_url");

	
	
	
	
	
});